/*
 License
 
 Copyright © 2012 Kevin Kimmich
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights to 
 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 the Software, and to permit persons to whom the Software is furnished to do so, 
 subject to the following conditions:
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
 FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include <sys/socket.h>
#include "crcore.h"

static uint32_t chunk_size = (DEFAULT_CHUNK_SIZE);

//stream from a file descriptor
void stream_from_file(stream* s, int fd, io_result* result, int* bytes_received)
{
	chunk_node_t* writer;

	lock_stream(s);
	if(s->allocated==0)
	{
		writer = chunk_malloc();
		list_add_tail(&s->chunks,&writer->node);
		s->allocated += chunk_size;
	}

	for(;;)
	{
		uint32_t offset = s->writer_length % chunk_size;
		uint32_t chunk_bytes_left = chunk_size - offset;
		writer = (chunk_node_t*)s->chunks.head.prev;
		void* stream_data = writer->data + offset;

		int err = read(fd,stream_data,chunk_bytes_left);
		
		if(err==0)//shutdown
		{
			*result = io_shutdown;
			unlock_stream(s);
			return;
		}
		
		if(err<0)//error is negative
		{
			switch(errno)
			{
				case EWOULDBLOCK:
				case ENOBUFS:
					unlock_stream(s);
					*result = io_would_block;
					return;
				case EINTR:
					continue;
				default:
				break;
			};
			unlock_stream(s);
			THROW(SOCKET_ERROR,"FD was closed");
		}
		
		*bytes_received += err;
		s->writer_length += err;
		
		if(err<chunk_bytes_left)
		{
			*result=io_would_block;
			unlock_stream(s);
			return;
		}
		list_add_tail(&s->chunks,(list_node_t*)chunk_malloc());
		s->allocated += chunk_size;
	}
	unlock_stream(s);
	*result = io_ok;
	return;
}

void stream_to_file(stream* s, int fd,io_result* result,int* bytes_sent)
{
	lock_stream(s);
	
	while(s->reader_length != s->writer_length)
	{
		chunk_node_t* reader = (chunk_node_t*)s->chunks.head.next;
		uint32_t stream_bytes_left = (s->writer_length - s->reader_length);
		uint32_t chunk_bytes_left = (chunk_size -  (s->reader_length % chunk_size));
		uint32_t bytes_to_write = chunk_bytes_left;
		uint32_t offset = s->reader_length % chunk_size;
		void* stream_ptr = reader->data + offset;
		
		if(stream_bytes_left < chunk_bytes_left)
			bytes_to_write = stream_bytes_left;
	
		int err = write(fd,stream_ptr,bytes_to_write);

		if(err <= 0)
		{
			if(errno==EWOULDBLOCK)
			{
				*result = io_would_block;
				unlock_stream(s);
				return;
			}
			unlock_stream(s);
			THROW(SOCKET_ERROR,"FD was closed");
		}
	
		*bytes_sent += err;
		s->reader_length += err;

		if(err < bytes_to_write)
		{
			*result = io_would_block;
			unlock_stream(s);
			return;
		}
		
		if(err==chunk_bytes_left)
		{
			list_remove(&s->chunks,&reader->node);
			chunk_free(reader);
			s->allocated -= chunk_size;
		}
	}
	unlock_stream(s);
	*result = io_ok;
}

//stream from a socket
void stream_from_socket(stream* s, int fd, io_result* result, int* bytes_received)
{
	chunk_node_t* writer;
	
	lock_stream(s);
	if(s->allocated==0)
	{
		writer = chunk_malloc();
		list_add_tail(&s->chunks,&writer->node);
		s->allocated += chunk_size;
	}
	
	for(;;)
	{
		uint32_t offset = s->writer_length % chunk_size;
		uint32_t chunk_bytes_left = chunk_size - offset;
		writer = (chunk_node_t*)s->chunks.head.prev;
		void* stream_data = writer->data + offset;
		
		int err = recv(fd,stream_data,chunk_bytes_left,MSG_PEEK);
		
		if(err<=0)
		{
			*result = io_closed;
			unlock_stream(s);
			THROW(SOCKET_ERROR,"Socket was closed on read");
			return;
		}
		
		err = recv(fd,stream_data,err,0);
		
		*bytes_received += err;
		s->writer_length += err;
		
		//if(err<chunk_bytes_left)
		{
			*result=io_ok;
			unlock_stream(s);
			return;
		}
		list_add_tail(&s->chunks,(list_node_t*)chunk_malloc());
		s->allocated += chunk_size;
	}
	unlock_stream(s);
	*result = io_ok;
	return;
}

void stream_from_ssl_socket(stream* s, SSL* ssl, io_result* result, int* bytes_received)
{
	chunk_node_t* writer;
	
	lock_stream(s);
	if(s->allocated==0)
	{
		writer = chunk_malloc();
		list_add_tail(&s->chunks,&writer->node);
		s->allocated += chunk_size;
	}
	
	for(;;)
	{
		uint32_t offset = s->writer_length % chunk_size;
		uint32_t chunk_bytes_left = chunk_size - offset;
		writer = (chunk_node_t*)s->chunks.head.prev;
		void* stream_data = writer->data + offset;
		
		int err = SSL_peek(ssl,stream_data,chunk_bytes_left);
		
		if(err<=0)
		{
			*result = io_closed;
			unlock_stream(s);
			THROW(SOCKET_ERROR,"Socket was closed on read");
			return;
		}
		
		err = SSL_read(ssl,stream_data,err);
		
		*bytes_received += err;
		s->writer_length += err;
		
		//if(err<chunk_bytes_left)
		{
			*result=io_ok;
			unlock_stream(s);
			return;
		}
		list_add_tail(&s->chunks,(list_node_t*)chunk_malloc());
		s->allocated += chunk_size;
	}
	unlock_stream(s);
	*result = io_ok;
	return;
}

void stream_to_socket(stream* s, int fd,io_result* result,int* bytes_sent)
{
	lock_stream(s);
	
	while(s->reader_length != s->writer_length)
	{
		chunk_node_t* reader = (chunk_node_t*)s->chunks.head.next;
		uint32_t stream_bytes_left = (s->writer_length - s->reader_length);
		uint32_t chunk_bytes_left = (chunk_size -  (s->reader_length % chunk_size));
		uint32_t bytes_to_write = chunk_bytes_left;
		uint32_t offset = s->reader_length % chunk_size;
		void* stream_ptr = reader->data + offset;
		
		if(stream_bytes_left < chunk_bytes_left)
			bytes_to_write = stream_bytes_left;
		
		int err = write(fd,stream_ptr,bytes_to_write);

		if(err <= 0)
		{
			unlock_stream(s);
			*result=io_closed;
			THROW(SOCKET_ERROR,"Socket was closed on write");
			return;
		}
		
		(*bytes_sent) += err;
		s->reader_length += err;
		
		if(err==chunk_bytes_left)
		{
			list_remove(&s->chunks,&reader->node);
			chunk_free(reader);
			s->allocated -= chunk_size;
		}
	}
	unlock_stream(s);
	(*result) = io_ok;
}

void stream_to_ssl_socket(stream* s, SSL* ssl,io_result* result,int* bytes_sent)
{
	lock_stream(s);
	
	while(s->reader_length != s->writer_length)
	{
		chunk_node_t* reader = (chunk_node_t*)s->chunks.head.next;
		uint32_t stream_bytes_left = (s->writer_length - s->reader_length);
		uint32_t chunk_bytes_left = (chunk_size -  (s->reader_length % chunk_size));
		uint32_t bytes_to_write = chunk_bytes_left;
		uint32_t offset = s->reader_length % chunk_size;
		void* stream_ptr = reader->data + offset;
		
		if(stream_bytes_left < chunk_bytes_left)
			bytes_to_write = stream_bytes_left;
		
		int err = SSL_write(ssl,stream_ptr,bytes_to_write);
		
		if(err <= 0)
		{
			unlock_stream(s);
			*result=io_closed;
			THROW(SOCKET_ERROR,"Socket was closed on write");
			return;
		}
		
		*bytes_sent += err;
		s->reader_length += err;
		
		if(err==chunk_bytes_left)
		{
			list_remove(&s->chunks,&reader->node);
			chunk_free(reader);
			s->allocated -= chunk_size;
		}
	}
	unlock_stream(s);
	*result = io_ok;
}


